#pragma once
#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;

    class Compiler
    {
    public:
        Compiler() {}
        ~Compiler() {}

        static bool Compile(const std::string &file_name)
        {
            pid_t pid = fork();
            if (pid < 0)
            {
                LOG(Loglevel::ERROR) << "内部错误, 编译时创建子进程失败\n";
                return false;
            }
            else if (pid == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::Compile_Error(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
                if (_stderr < 0)
                {
                    LOG(Loglevel::WARN) << "编译时, 没有成功形成stderr文件\n";
                    exit(1);
                }
                dup2(_stderr, 2);

                execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(), PathUtil::Src(file_name).c_str(), "-D", "COMPILER_ONLINE", "-std=c++11", nullptr);
                LOG(Loglevel::ERROR) << "编译时程序替换失败, 可能参数传递错误\n";
                exit(2);
            }
            else
            {
                pid_t rid = waitpid(pid, nullptr, 0);
                // 检查是否编译成功
                if (FileUtil::IsFileExists(PathUtil::Exe(file_name)))
                {
                    LOG(Loglevel::INFO) << "编译成功\n";
                    return true;
                }
                LOG(Loglevel::INFO) << "可执行文件不存在，编译失败\n";
                return false;
            }
        }
    };
}